package com.ruicar.afs.cloud.basic.cms.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.basic.common.entity.*;
import com.ruicar.afs.cloud.basic.common.service.*;
import com.ruicar.afs.cloud.basic.common.vo.TotalReceivableVo;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.contract.enums.FeeTypeEnum;
import com.ruicar.afs.cloud.common.modules.contract.enums.PersonRoleTypeEnum;
import com.ruicar.afs.cloud.common.modules.contract.enums.ReceiptStatusEnum;
import com.ruicar.afs.cloud.common.util.EmptyUtils;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.List;

/**
 * @author: Lee
 * @date: 2020/5/11 19:39
 * @description: 多品合同对接聚合层 应收总计
 */
@Slf4j
@RestController
@RequestMapping("/icosReceivable")
@AllArgsConstructor
public class IcosReceivableController {

    private final BasicMainInfoService basicMainInfoService;
    private final BasicChannelInfoService basicChannelInfoService;
    private final BasicCustBaseInfoService basicCustBaseInfoService;
    private final BasicContractCustRelationService basicContractCustRelationService;
    private final BasicRepaymentPlanService basicRepaymentPlanService;
    private final BasicReceiptRecordService basicReceiptRecordService;
    private final BasicExpenseRecordService basicExpenseRecordService;

    @ApiOperation(value = "应收总计")
    @PostMapping("/getReceivable")
    public IResponse<TotalReceivableVo> getReceivable(@RequestParam("contractNo") String contractNo){
        if (EmptyUtils.isEmpty(contractNo)){
            return IResponse.fail("合同编号不能为空");
        }
        TotalReceivableVo totalReceivableVo = new TotalReceivableVo();
        /**  基本信息 by ZC.GUO  **/
        BasicMainInfo mainInfo = basicMainInfoService.getOne(Wrappers.<BasicMainInfo>query().lambda()
                .eq(BasicMainInfo::getContractNo,contractNo)
        );
        if (EmptyUtils.isEmpty(mainInfo)){
            return IResponse.fail("未找到对应合同");
        }else{
            totalReceivableVo.setContractNo(mainInfo.getContractNo());
            totalReceivableVo.setContractStatus(mainInfo.getContractStatus());
            totalReceivableVo.setProductName(mainInfo.getProductName());
        }
        /**  基本信息 by ZC.GUO  **/
        List<BasicChannelInfo> channelInfos = basicChannelInfoService.list(Wrappers.<BasicChannelInfo>query().lambda()
                .eq(BasicChannelInfo::getContractNo,contractNo)
        );
        if (EmptyUtils.isEmpty(channelInfos)){
            return IResponse.fail("未找到对应合作商");
        }else{
            totalReceivableVo.setChannelName(channelInfos.get(0).getContactName());
        }
        /**  客户信息 by ZC.GUO  **/
        BasicContractCustRelation contractCustRelation = basicContractCustRelationService.getOne(Wrappers.<BasicContractCustRelation>query().lambda()
                .eq(BasicContractCustRelation::getContractNo,mainInfo.getContractNo())
                .eq(BasicContractCustRelation::getCustRole, PersonRoleTypeEnum.MAIN_PERSON)
        );
        if (EmptyUtils.isNotEmpty(contractCustRelation)){
            BasicCustBaseInfo custBaseInfo = basicCustBaseInfoService.getOne(Wrappers.<BasicCustBaseInfo>query().lambda()
                    .eq(BasicCustBaseInfo::getCustNo,contractCustRelation.getCustNo())
            );
            if (EmptyUtils.isNotEmpty(custBaseInfo)){
                totalReceivableVo.setCustName(custBaseInfo.getCustName());
            }
        }
        /**  还款信息 by ZC.GUO  **/
        BasicRepaymentPlan repaymentPlan = basicRepaymentPlanService.calculateRepaymentInfo(basicRepaymentPlanService.list(Wrappers.<BasicRepaymentPlan>query().lambda()
                .eq(BasicRepaymentPlan::getContractNo,mainInfo.getContractNo())
                .ne(BasicRepaymentPlan::getTermNo, BigDecimal.ZERO.intValue())
                .orderByAsc(BasicRepaymentPlan::getTermNo)
        ));
        if (EmptyUtils.isNotEmpty(repaymentPlan)){
            totalReceivableVo.setTotalUnpaidInterest(String.valueOf(repaymentPlan.getTotalUnpaidInterest()));
            totalReceivableVo.setTotalPaidRent(repaymentPlan.getTotalPaidRent());
            totalReceivableVo.setTotalUnpaidPrinciple(repaymentPlan.getTotalUnpaidPrinciple());
            totalReceivableVo.setPaidPrinciple(repaymentPlan.getPaidPrinciple());
            totalReceivableVo.setPaidInterest(repaymentPlan.getPaidInterest());
            totalReceivableVo.setTotalUnpaidRent(repaymentPlan.getUnpaidRent());
        }

        /**  预付金额和未偿罚息 by ZC.GUO  **/
        totalReceivableVo.setTotalUnusedAmt(BigDecimal.ZERO);
        List<BasicReceiptRecord> receiptRecordList = basicReceiptRecordService.list(Wrappers.<BasicReceiptRecord>query().lambda()
                .eq(BasicReceiptRecord::getContractNo,mainInfo.getContractNo())
                .eq(BasicReceiptRecord::getReceiptStatus, ReceiptStatusEnum.creditSuccess)
                .gt(BasicReceiptRecord::getUnusedAmt,BigDecimal.ZERO)
        );
        if (EmptyUtils.isNotEmpty(receiptRecordList)){
            receiptRecordList.forEach(receiptRecord -> {
                totalReceivableVo.setTotalUnusedAmt(totalReceivableVo.getTotalUnusedAmt().add(receiptRecord.getUnusedAmt()));
            });
        }
        List<BasicExpenseRecord> expenseCostRecordList = basicExpenseRecordService.list(Wrappers.<BasicExpenseRecord>query().lambda()
                .eq(BasicExpenseRecord::getContractNo,mainInfo.getContractNo())
                .ne(BasicExpenseRecord::getCostType, FeeTypeEnum.penalty)
                .gt(BasicExpenseRecord::getRemainingAmt,BigDecimal.ZERO)
        );
        if (EmptyUtils.isNotEmpty(expenseCostRecordList)){
            expenseCostRecordList.forEach(expenseRecord -> {
                totalReceivableVo.setTotalUnpaidCost(totalReceivableVo.getTotalUnpaidCost().add(expenseRecord.getRemainingAmt()));
            });
        }
        totalReceivableVo.setTotalUnpaidPenalty(BigDecimal.ZERO);
        List<BasicExpenseRecord> expenseRecordList = basicExpenseRecordService.list(Wrappers.<BasicExpenseRecord>query().lambda()
                .eq(BasicExpenseRecord::getContractNo,mainInfo.getContractNo())
                .eq(BasicExpenseRecord::getCostType, FeeTypeEnum.penalty)
                .gt(BasicExpenseRecord::getRemainingAmt,BigDecimal.ZERO)
        );
        if (EmptyUtils.isNotEmpty(expenseRecordList)){
            expenseRecordList.forEach(expenseRecord -> {
                totalReceivableVo.setTotalUnpaidPenalty(totalReceivableVo.getTotalUnpaidPenalty().add(expenseRecord.getRemainingAmt()));
            });
        }
        /**  计算未偿总额 by ZC.GUO  **/
        totalReceivableVo.setTotalUnpaid((EmptyUtils.isNotEmpty(totalReceivableVo.getTotalUnpaidRent())?totalReceivableVo.getTotalUnpaidRent():BigDecimal.ZERO)
                .add(EmptyUtils.isNotEmpty(totalReceivableVo.getTotalUnpaidPenalty())?totalReceivableVo.getTotalUnpaidPenalty():BigDecimal.ZERO)
                .add(EmptyUtils.isNotEmpty(totalReceivableVo.getTotalUnpaidCost())?totalReceivableVo.getTotalUnpaidCost():BigDecimal.ZERO));
        return IResponse.success(totalReceivableVo);

    }

}
